
#include "grid_sample.h"
#include "utils.h"
GridSample::GridSample() noexcept {}

GridSample::~GridSample() {
  destory();
}

uint32_t GridSample::Run(DataBuf& data_frame) noexcept {
  uint32_t Rval = SetInput(data_frame.pre_input.first, data_frame.pre_input.second, GridSample::InputType::PRE_INPUT);
  if (Rval != 0U) {
    Print("Error encounted when handling PRE_INPUT! size = %ld ...\n", data_frame.pre_input.second);
    return 1;
  }
  Rval |= SetInput(data_frame.align_matrix.first, data_frame.align_matrix.second, GridSample::InputType::ALIGN_MATRIX);
  if (Rval != 0U) {
    Print("Error encounted when handling align_matrix! size = %ld ...\n", data_frame.align_matrix.second);
    return 1;
  }


  auto end_time_2 = CV_FlexidagTimestamp();
  Rval = RunBlock();
  auto end_time_3 = CV_FlexidagTimestamp();
  Print("Time of >> grid_sample << : %d us.\n",
         end_time_3 - end_time_2);
  return Rval;
}

void GridSample::test() {
  std::uint32_t Rval = 0;
  std::string pre_input_path = "./pre_input.bin";
  std::string align_matrix_path = "./align_matrix_path.bin";

  // step4.3 把第一段网络的运行结果送给第二段
  auto start_time_2 = CV_FlexidagTimestamp();
  Rval |= SetInput(pre_input_path, InputType::PRE_INPUT);
  Rval |= SetInput(align_matrix_path, InputType::ALIGN_MATRIX);
  auto end_time_2 = CV_FlexidagTimestamp();

  // step4.4 跑第三段网络
  auto start_time_3 = CV_FlexidagTimestamp();
  Rval = AmbaCV_FlexidagRun(&handle_, &in_buf_, &out_buf_, &run_info_);
  auto end_time_3 = CV_FlexidagTimestamp();
  for (int i = 0; i < out_buf_.num_of_buf; i++) {
    Rval = AmbaCV_UtilityCmaMemInvalid(&out_buf_.buf[i]);
  }
}

bool GridSample::SetInput(std::string const &path,
                          InputType input_type) noexcept {
  return 0 == LoadInPutFile(path, input_type, &raw_, &inputblk_[input_type]);
}
bool GridSample::SetInput(char *input_buffer, std::uint32_t buffer_size,
                          InputType input_type) noexcept {
  return 0 == LoadInPutBuffer(input_buffer, buffer_size, input_type, &raw_,
                              &inputblk_[input_type]);
}

std::uint32_t GridSample::free_all_buffer() {
  std::uint32_t Rval = 0U;

  for (std::uint8_t i = 0; i < InputType::Count; ++i) {
    Rval |= AmbaCV_UtilityCmaMemFree(&inputblk_[i]);
  }

  // Rval |= AmbaCV_UtilityCmaMemFree(&cat2491);
  // Rval |= AmbaCV_UtilityCmaMemFree(&cat2492);


  if (Rval != 0U) {
    printf("GridSample free_all_buffer fail (0x%x)\n", Rval);
  }
  return Rval;
}
